import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import external.Message;
import external.Player;


public class NET {
	public static volatile Boolean startGame=false;
	private static Socket socket = new Socket();
	/*public NET(){
		socket = new Socket();
	}*/
	public static int[] Connect(String IP, int port)
	{
		Message message = null;
		try {
			InetSocketAddress address = new InetSocketAddress(IP,port);
			socket.connect(address);// = new Socket(IP,port);
			message = ReadData(socket);
						
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			System.out.println("1Connect");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("2Connect");
			e.printStackTrace();
		}
		if(message!=null) return (int[])message.messageInfo;
		else return null;
	}
	public static void ToggleGameStart()
	{
		startGame = true;
	}
	public static int[] JoinToRoom(int roomNumber)
	{
		Message message = new Message(Message.Type.JoinRoom,new Integer(roomNumber));
		SendData(socket, message);
		Message readMessage = ReadData(socket);
		new Thread(new SocketListener(socket, startGame)).start();
		return (int[])readMessage.messageInfo;
	}
	
	public static Player[] SendStats(Player playerState)
	{
		Message message = new Message(Message.Type.selfState,playerState);
		SendData(socket, message);
		Message readMessage = ReadData(socket);
		return (Player[])readMessage.messageInfo;
	}
	private static Message ReadData(Socket socket)
	{
		Message data = null;
		try {
			InputStream is = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			data = (Message)ois.readObject();
//			ois.close();
//			is.close();
		} catch (IOException  e) {
			// TODO Auto-generated catch block
			System.out.println("1ReadData");
			e.printStackTrace();
		}  catch (ClassNotFoundException  e) {
			// TODO Auto-generated catch block
			System.out.println("2ReadData");
			e.printStackTrace();
		}
		return data;
	}
	private static void SendData(Socket socket, Message message)
	{
		try {
			OutputStream os = socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(message);
			oos.flush();
/*			oos.close();
			os.close();*/
		} catch (IOException e) {
			System.out.println("1SendData");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
